<template>
  <div class="app-container">
    <el-card class="chat-container">
      <div class="chat-messages" ref="messageContainer">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
          <div class="message-content">{{ message.content }}</div>
        </div>
      </div>
      <div class="chat-input">
        <el-input
          v-model="question"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
          @keyup.enter.native="handleSend"
        />
        <el-button type="primary" @click="handleSend" :loading="loading">发送</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: "FaqChat",
  data() {
    return {
      question: '',
      messages: [],
      loading: false
    }
  },
  methods: {
    handleSend() {
      if (!this.question.trim()) {
        return
      }

      // 添加用户问题到消息列表
      this.messages.push({
        type: 'user',
        content: this.question
      })

      this.loading = true

      // 发送请求获取答案
      request({
        url: '/faq/ask',
        method: 'post',
        data: this.question
      }).then(response => {
        // 添加系统回答到消息列表
        this.messages.push({
          type: 'system',
          content: response.msg
        })
      }).catch(error => {
        this.messages.push({
          type: 'system',
          content: '抱歉，系统出现错误，请稍后重试。'
        })
      }).finally(() => {
        this.loading = false
        this.question = ''
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      })
    },
    scrollToBottom() {
      const container = this.$refs.messageContainer
      container.scrollTop = container.scrollHeight
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: calc(100vh - 200px);
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message {
  margin-bottom: 20px;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 10px;
  word-break: break-word;
}

.message.user .message-content {
  background-color: #409EFF;
  color: white;
}

.message.system .message-content {
  background-color: #f4f4f5;
  color: #333;
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
}

.chat-input .el-button {
  align-self: flex-end;
}
</style>
